Provider配合Dio获取网络数据

本文介绍了一种在Flutter中使用ChangeNotifier管理状态的方法。通过混入ChangeNotifier类,可以创建一个数据模型类GetDatawithChangeNotifier,该类能自动管理所有监听者。文章详细展示了如何在该类中存储和获取数据,以及如何在UI组件中展示这些数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据模型类的定义
//使用mixin混入ChangeNotifier类,这个类能够自动管理所有听众.
class GetData with ChangeNotifier {
//存储数据
  String _title;
  String _answerA;

  //提供外部能够访问的数据
  String get title => _title;
  String get answerA => _answerA;

  //提供更改数据的方法
  void getTitleList() async {
    //请求url
    var url =
        'http://api.xxx.com/xxx/xxx/index?key=xxxxx72b89c';
    //调用请求方法传入url
    await request(url).then((value) {
      //Json解码 value为服务端返回的数据
      var data = json.decode(value.toString());
      //打印数据
      print('获取的数据Json格式:::' + data.toString());
      //将Json数据转换成ProductListModel
      ProductListModel productList = ProductListModel.fromJson(data);
      //将返回的数据放入ProductProvider里
      if (productList.newslist == null) {
        // Provider.of<Counter>(context).getProductList([]);
      } else {
        // Provider.of<Counter>(context).getProductList(productList.data);
        _title = productList.newslist[0].title;
        _answerA = productList.newslist[0].answer;
      }
    });
    //通知所有听众进行刷新
    notifyListeners();
  }
}
展示和获取网络数据
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("${Provider.of<GetData>(context).title}"), //展示数据
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _changQuestion,
        tooltip: 'Increment',
        child: Icon(Icons.refresh),
      ),
    );
  }

    void _changQuestion() {
    setState(() {
      Provider.of<GetData>(context).getTitleList(); //获取数据
    });
  }


}

每次初始化时,没有获取到数据,显示null

在build里判断一次,如果是null则调用.

if(Provider.of<GetData>(context).title != null ) {

    } else {
         Provider.of<GetData>(context).getTitleList();
    }

如果不加判断,则会无限调用.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值