简体   繁体   中英

Flutter package provider with templates

I'm trying to use provider with template, but Provider.of seems not working like that.

Logs:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following ProviderNotFoundError was thrown building MyChildWidget(dirty): Error: Could not find the correct Provider above this MyChildWidget Widget

To fix, please:

  • Ensure the Provider is an ancestor to this MyChildWidget Widget
  • Provide types to Provider
  • Provide types to Consumer
  • Provide types to Provider.of()
  • Always use package imports. Ex: `import 'package:my_app/my_code.dart';
  • Ensure the correct context is being used.

Do you know any solution ?

Sample to show the problem:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Provider<MyChildState>.value(
          value: MyChildState("Hello world !"),
          child: MaterialApp(
            home: MyChildWidget(),
          )),
    );
  }
}

abstract class MyParentWidget<State extends MyParentState> extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final State state = Provider.of(context);
    return Text(state.text);
  }
}

abstract class MyParentState {
  final String text;

  MyParentState(this.text);
}

class MyChildWidget<MyChildState> extends MyParentWidget{
}

class MyChildState extends MyParentState {
  MyChildState(String text) : super(text);
}

At a first glance over your code, I can see that you are passing MyChildState("Hello world !") as the value, but later in MyParentWidget class you are requesting a State object final State state = Provider.of(context); .

Try requesting MyChildState instead of State .

My first impression after reading your code is that you are coming from a different programming language and now you are trying Flutter. A friendly advice would be keep everything as simple as possible .

All the abstraction and how the code is organized might confuse you later when you review the code you wrote instead of helping you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM