Home > Net >  How can I pass data from a TextFieldInput to another Page with Provider
How can I pass data from a TextFieldInput to another Page with Provider

Time:05-23

I want to pass the Data (String) from a TextField to a second Page with Provider after I clicked the Button.

Here is my code

CodePudding user response:

Update your name_provider class

class NameProvider extends ChangeNotifier {
  String _name = "";

  String get getName => _name;

  saveName(String name) {
    _name = name;
    notifyListeners();
  }
}

The name variable was made private to avoid getting wrong result while calling the function.

Now this edit was made to main.dart file

class _MyHomePageState extends State<MyHomePage> {
  String name = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'Please enter your name',
              ),
              TextField(
                onSubmitted: (value) {
                  setState(() {
Provider.of<NameProvider>(context).saveName(value);
                  });
                },
                onChanged: (value) {
                  setState(() {
                    name = value;
                  });
                },
              ),
              Text("Name: $name"),
              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const SecondPage(),
                    ),
                  );
                },
                child: const Text("To Second Page"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Now getting name in SecondPage:

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Page"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              Text(
                "Name:",
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              Text(
                
                Provider.of<NameProvider>(context).getName,
                style: TextStyle(fontSize: 32),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

If there is some sort of expected string but got... error, replace getName with '${Provider.of<NameProvider>(context).getName}'

Let us know if this solution works

CodePudding user response:

First of all, in the main.dart file at line 70, do this:

Provider.of<NameProvider>(context).saveName(name);

and then on the second page where you want to use this Provider.of<NameProvider>(context).name;

CodePudding user response:

Here is the full working code.

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

class ProviderCheck extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => NameProvider(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Provider Problem'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String name = "";
//it will store data in typed in textfield
  final TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'Please enter your name',
              ),
              TextField(
                controller: _textEditingController,//texteditingcontroller set to textfield
                onSubmitted: (value) {
                  setState(() {
                    name = value;
                  });
                },
                onChanged: (value) {
                  setState(() {
                    name = value;
                  });
                },
              ),
              Text("Name: $name"),
              TextButton(
                onPressed: () {
                  //saveName method called using provider and name saved.
                  Provider.of<NameProvider>(context, listen: false)
                      .saveName(_textEditingController.text);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const SecondPage(),
                    ),
                  );
                },
                child: const Text("To Second Page"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class NameProvider extends ChangeNotifier {
  String name = "";

  String get getName => name;
//name1 value will set to name variable
  saveName(String name1) {
    name = name1;
    notifyListeners();
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Page"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              //using provider, we can access the saved name
              Text(
                "Name:${Provider.of<NameProvider>(context, listen: false).getName}",
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              Text(
                //TODO: Name should be displayed here
                "Name",
                style: TextStyle(fontSize: 32),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


CodePudding user response:

if you prefer to use provider for that purpose, edit your provider saveName Function to :

  saveName(String _name) {
    name = _name;
    notifyListeners();
  }

in SecondPage() add your provider to the build method like this :

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
  final nameProvider = Provider.of< NameProvider>(context);

then get your string value by calling :

    Text(
      "Name: ${nameProvider.name}",
      style : ....
  • Related