首页 > 解决方案 > Flutter Changenotifier 类总是需要在我的函数中传递

问题描述

我有一个FutureBuilder从函数接收值。这是我FutureBuilder的新context.watch语法

final dataNotifier = Provider.of<DataNotifier>(context, listen: false);
    returnFutureBuilder(
                future: DataService().getData(dataNotifier),
                // ignore: missing_return
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                      return Center(child: Text('No status', style: TextStyle(color: Colors.white),));
                      break;
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator());
                      break;
                    case ConnectionState.done:
                    
    
                    return Center(
                      child:  Column(
                                    children: [
                                      Text(context.watch<Data>().myList[0].id, style: TextStyle(color: Colors.white)),
                                      Text(context.watch<Data>().myList[0].name, style: TextStyle(color: Colors.white))
                                    ],
                    ));
                   
                       //Center(child: Text('Data', style: TextStyle(color: Colors.white),));
                      break;
                    default:
                  }
                },
              ),

只要我总是dataNotifier在每个函数中传递,一切都可以正常工作。我对提供者还不是很熟悉,我怎样才能在不总是通过的情况下完成这项工作dataNotifier

我假设我必须在我的 Changenotifier 类中添加一些东西?我未来的功能getData(dataNotifier)以以下结束:

dataNotifier.myList = _myList;

我的ChangenotifierDataNotifier

class DataNotifier with ChangeNotifier {


      List<Data> _myList = [];
      UnmodifiableListView<Data> get myList => UnmodifiableListView(_myList);
      set myList(List<Data> myList){
        _myList = myList;
        notifyListeners();
      }

标签: flutterflutter-provider

解决方案


具有 MVVM(模型、视图、视图模型)架构的最简单的 Provider 示例如下所示。

加载数据时,应用程序会更新以显示新值。

您可以将字符串数据替换为您喜欢的任何内容,例如项目列表。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MaterialApp(
      home: Material(
    child: ChangeNotifierProvider<DataNotifier>(
        create: (_) => DataNotifier(), child: MyApp()),
  )));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final dataNotifier = Provider.of<DataNotifier>(context);
    if (dataNotifier.dataLoaded) return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: [
      Text(dataNotifier.data),
      Text(
      dataNotifier.listData.fold("LIST: ", (previousValue, e) => "$previousValue [${e.id} ${e.name}]"),
    )]);
    return Text("Waiting...");
  }
}

class DataNotifier with ChangeNotifier {
  bool _dataLoaded;
  bool get dataLoaded => _dataLoaded;
  DataService _service;
  String _data;
  String get data => _data;
  List<SampleData> _listData;
  List<SampleData> get listData => _listData;

  DataNotifier() {
    _dataLoaded = false;
    _service = DataService();
    getData();
  }

  void getData() async {
    _data = await _service.getData();
    _listData = await _service.getListData();
    _dataLoaded = true;
    notifyListeners();
  }
}

class DataService {
  Future<String> getData() async {
    return Future<String>.delayed(
      const Duration(seconds: 5),
      () => 'Data Loaded',
    );
  }

  Future<List<SampleData>> getListData() async {
    return Future<List<SampleData>>.delayed(
      const Duration(seconds: 5),
      () => List.generate(100, (index) => SampleData(index, "name_$index")),
    );
  }
}

class SampleData {
  int id;
  String name;

  SampleData(this.id, this.name);
}

推荐阅读