Pass an object through navigator.pushnamed using provider

Here is an example of how you can pass an object through a route using the Navigator.pushNamed() method and Provider in Flutter:

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

class MyObject {
  final int id;
  final String name;

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

class MyObjectProvider extends ChangeNotifier {
  MyObject _object;

  MyObject get object => _object;

  set object(MyObject value) {
    _object = value;
    notifyListeners();
  }
}

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => MyObjectProvider(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/detail': (context) => DetailPage(),
      },
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            final object = MyObject(1, 'Object');
            Provider.of<MyObjectProvider>(context, listen: false).object = object;
            Navigator.of(context).pushNamed('/detail');
          },
          child: Text('Go to detail page'),
        ),
      ),
    );
  }
}

class DetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final object = Provider.of<MyObjectProvider>(context).object;
    return Scaffold(
      body: Center(
        child: Text('Object ID: ${object.id}'),
      ),
    );
  }
}

In this example, the MyObject class represents an object that you want to pass through a route. The MyObjectProvider class is a ChangeNotifier that holds the MyObject object and exposes it to other widgets through a getter method.

The HomePage widget has a button that, when clicked, sets the MyObject object in the MyObjectProvider using the object setter method

Did this tutorial help a little? How about buy me a cup of coffee?

Buy me a coffee at ko-fi.com

Please feel free to use the comments form below if you have any questions or need more explanation on anything. I do not guarantee a response.

IMPORTANT: You must thoroughy test any instructions on a production-like test environment first before trying anything on production systems. And, make sure it is tested for security, privacy, and safety. See our terms here.

tags cloud icon tags cloud

dart

popular searches icon popular searches