Is FutureProvider broken or something?

ⅰ亾dé卋堺 提交于 2020-04-18 05:50:48

问题


I try this simple FutureProvider code yet it gave me an error:

Error: Could not find the correct Provider<String> above this Consumer<String> Widge

I have make sure that FutureProvider wraps my MaterialApp and get the provider using Consumer widget.

Here's my code:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureProvider(
      create: (_) => Future.value('test'),
      catchError: (_, error) => print(error),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.amber,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home(),
      ),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Consumer<String>(builder: (context, string, _) {
          return Text(string);
        }),
      ),
    );
  }
}

Did I miss something here?


回答1:


The error is quite descriptive of what is happening, you are trying to consume a String, and you don't have a provider of String.

If instead of FutureProvider(...etc you write FutureProvider<String>(...etc your IDE will point out that the catchError returns Void. This means that you return a String in create and Void in catchError, making the provider of type dynamic.

To solve this, make catchError return 'error', or anything that you choose, as long as it is a String.

      catchError: (_, error) { 
          print(error);
          return 'error';
          },

Edit

As the first comment points out, you will still get an error. As the FutureProvider doesn't have an initialValue, it is set to null. This means that the very first run will pass a null value to the text Widget.

This can be prevented by setting the initialValue of FutureProvider to 'loading...' for example.



来源:https://stackoverflow.com/questions/61196212/is-futureprovider-broken-or-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!