提供者的状态管理非常慢

时间:2021-04-30 07:13:15

标签: flutter state flutter-provider

我在我的应用程序中使用 Provider 进行状态管理,当我将数据发送到 api 时它工作正常,但是当在我的屏幕上显示数据需要 1 到 3 分钟时,这里是我的代码:

class ListService extends ChangeNotifier {
  Future<List<ListModel>> fetchLists(String url) async {
    Response response = await get(Uri.parse(url));

    if (response.statusCode == 200) {
      List<dynamic> body = jsonDecode(response.body);

      List<ListModel> lists =
          body.map((dynamic list) => ListModel.fromJson(list)).toList();

      notifyListeners();

      return lists;
    } else {
      throw "can't get lists";
    }
  }

  Future<Response> createList(AddList listModel) async {
    Map<String, String> headers = {'Content-Type': 'application/json'};
    String jsEncode;
    jsEncode = jsonEncode(listModel);
    final Response response = await post(
      Uri.parse('https://elerdigt-api.azurewebsites.net/api/lists'),
      headers: headers,
      body: jsEncode,
    );
    notifyListeners();
    return response;
  }
}

这里是我的 main.dart

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => ListService(),
        ),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          scaffoldBackgroundColor: Color(0xffb591fff),
          fontFamily: 'MontSerrat',
        ),
        home: HomeScreen(),
      ),
    );
  }
}

这是我获取数据的地方

Widget listofLists(Future<List<ListModel>> lists) {
  return CustomContainer(
    child: FutureBuilder(
      future: lists,
      builder: (BuildContext context, AsyncSnapshot<List<ListModel>> snapshot) {
        if (snapshot.hasData) {
          List<ListModel> lists = snapshot.data!;

          return lists.length < 1
              ? Center(
                  child: Text(
                    "you haven't created a new List yet ,\n please tap '+' to add create a new one",
                    textAlign: TextAlign.center,
                  ),
                )
              : ListView(
                  children: lists
                      .map(
                        (ListModel list) => Container(
                          child: Text(list.name!),
                        ),
                      )
                      .toList(),
                );
        }
        return Center(
          child: CircularProgressIndicator(),
        );
      },
    ),
  );
}

最后的画面

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: listofLists(
        Provider.of<ListService>(context)
            .fetchLists('https://elerdigt-api.azurewebsites.net/api/lists'),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloatand ,
      floatingActionButton: button(
        context,
        addListForm(context),
        150.0,
      ),
    );
  }
}

添加数据的表单

TextEditingController _controller = TextEditingController();

Widget addListForm(BuildContext context) {
  return Form(
    child: Column(
      children: [
        TextFormField(
          controller: _controller,
          decoration: InputDecoration(
            hintText: 'create a new list',
            border: InputBorder.none,
          ),
        ),
        SizedBox(
          height: 20.0,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text("cancel"),
            ),
            SizedBox(
              width: 10.0,
            ),
            TextButton(
                onPressed: () {
                  AddList newList = AddList(
                    userId: 'PierreEdimo',
                    name: _controller.text,
                    emojiUrl: '☰',
                  );

                  Provider.of<ListService>(context, listen: false)
                      .createList(newList);

                  Navigator.of(context).pop();
                },
                child: Text(
                  "save",
                ))
          ],
        )
      ],
    ),
  );
}

通常不应该这么慢,我做错了什么吗?我该怎么做才能更快地获取数据

0 个答案:

没有答案