Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

the provider instance cannot be obtained correctly in methodChannel.setMethodCallHandler #877

Closed
huxiaofan1223 opened this issue Apr 28, 2024 · 1 comment
Assignees
Labels
bug Something isn't working needs triage

Comments

@huxiaofan1223
Copy link

Describe the bug
A clear and concise description of what the bug is.

To Reproduce

class MainActivity : FlutterActivity() {
    private final val CHANNEL = "com.example/mediaControl";
    private lateinit var flutterEngine: FlutterEngine;
    lateinit var channel:MethodChannel;
    private fun invokeToFlutter(val: String) {
        channel.invokeMethod(
            "invokeToFlutter",
            val
        )
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        flutterEngine = FlutterEngine(this);
        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
        channel = MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
        Handler().postDelayed({
            invokeToFlutter("countAdd");
        }, 3000)
        super.onCreate(savedInstanceState)
    }
}
void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Counter()),
      ],
      child: const MyApp(),
    ),
  );
}
class Counter with ChangeNotifier, DiagnosticableTreeMixin {
  int _count = 0;
  int get count => _count;
  void increment() {
    _count++;
    notifyListeners();
  }
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    const MethodChannel _channel = MethodChannel('com.example/mediaControl');
    _channel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'invokeToFlutter':
          if (call.arguments == 'countAdd') {
            Provider.of<Counter>(context, listen: false).increment();
            print('receive: countAdd');
            print('receive: ${Provider.of<Counter>(context, listen: false).count}');
          }
          break;
        default:
          throw UnimplementedError();
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('${context.watch<Counter>().count}')
          ],
        ),
      )
    );
  }
}

Expected behavior
The increment method was called,but the count was not updated
It seems like the instance of Counter was taken incorrectly

Where was the problem with my code

@rrousselGit
Copy link
Owner

Provider has nothing to do with MethodChannels. For general help requests, consider using StackOverflow or Discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs triage
Projects
None yet
Development

No branches or pull requests

2 participants