美文网首页
网络请求+模型处理

网络请求+模型处理

作者: xieyinghao | 来源:发表于2023-06-05 07:26 被阅读0次
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    
    import 'Counter.dart';
    
    void main() {
      // runApp(const MyApp());
      runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => Counter()),
          ],
          child: const MyApp(),
        ),
      );
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        // setState(() {
        //   _counter++;
        // });
        context.read<Counter>().increment();
      }
    
      Future getHomePage() async {}
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        context.read<Counter>().requestData();
      }
    
      @override
      Widget build(BuildContext context) {
        context.read<Counter>().onReqList;
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // const Text(
                //   // 'You have pushed the button this many times:',
                //   '${context.watch<Counter>().count}',
                // ),
                Text(
                  // '${context.watch<Counter>().count}',
                  '${context.watch<Counter>().model?.city ?? "-"}',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    }
    
    

    业务控制器

    import 'package:dio/dio.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_provide/tianqi.dart';
    
    enum BaseCcontrollerStatus {
      empty,
      loading,
      success,
      fail,
    }
    
    class Counter with ChangeNotifier {
      int _count = 0;
      int get count => _count;
    
      WeaModel? _model;
      WeaModel? get model => _model;
    
      BaseCcontrollerStatus _status = BaseCcontrollerStatus.loading;
      BaseCcontrollerStatus get status => _status;
    
      void increment() {
        _count++;
        notifyListeners();
      }
    }
    
    extension Network on Counter {
      void onReqList() async {
        Future.delayed(const Duration(seconds: 2), () {
          _status = BaseCcontrollerStatus.success;
          // print('初始化请求啦:9999999');
          notifyListeners();
        });
      }
    }
    
    extension Network1 on Counter {
      void requestData() async {
        print('初始化请求啦');
        var dio = Dio();
        final response = await dio.get(
            'https://www.tianqiapi.com/free/day?appid=23035354&appsecret=8YvlPNrz');
        WeaModel model = WeaModel.fromJson(response.data);
        _model = model;
        print(response.data);
        print('哈哈${model.city}');
        print('初始化请求完成啦');
        notifyListeners();
      }
    }
    //https://pub.flutter-io.cn/packages/provider/example    provider使用例子
    
    

    模型

    class WeaModel {
      num? nums;
      String? cityid;
      String? city;
      String? date;
      String? week;
      String? updateTime;
      String? wea;
      String? weaImg;
    
      WeaModel(
          {this.nums,
          this.cityid,
          this.city,
          this.date,
          this.week,
          this.updateTime,
          this.wea,
          this.weaImg});
    
      WeaModel.fromJson(Map<String, dynamic> json) {
        nums = json['nums'];
        cityid = json['cityid'];
        city = json['city'];
        date = json['date'];
        week = json['week'];
        updateTime = json['update_time'];
        wea = json['wea'];
        weaImg = json['wea_img'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['nums'] = this.nums;
        data['cityid'] = this.cityid;
        data['city'] = this.city;
        data['date'] = this.date;
        data['week'] = this.week;
        data['update_time'] = this.updateTime;
        data['wea'] = this.wea;
        data['wea_img'] = this.weaImg;
        return data;
      }
    }
    
    

    相关文章

      网友评论

          本文标题:网络请求+模型处理

          本文链接:https://www.haomeiwen.com/subject/niqvedtx.html