Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse the contents of the same widget in flutter?

Tags:

flutter

dart

I want to use the same instance of a widget in multiple places, changes in one place will be synchronized to another place.

But using the same instance in multiple places looks like multiple different instances.

So how can I achieve the feat?

  var test = InAppWebView(
    // ...
  );

  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        children: [
          test,  // widget one
          test,  // widget two
        ],
        controller: _pageController,
        physics: NeverScrollableScrollPhysics(),
        onPageChanged: onPageChanged,
      ),
     ),
    }

I'm use flutter_inappbrowser.

Widget one and widget two use the same instance, but when I open the web page with widget one, widget two is unaffected.

I want widget one and widget two to be the same widget, that when widget one changes, widget two will also be affected.

like image 218
Martin Zhu Avatar asked May 21 '19 07:05

Martin Zhu


People also ask

How do I recreate widgets in Flutter?

You can now rebuild a widget even when Flutter fails to do so. Flutter uses setState() to reference the state object and identify any change to the state. This way, you can track these changes and rebuild your application. In case this fails, keys will play an important role in forcing a rebuild of any preserved state.

Which widget is used for repeating the content in Flutter?

Repeaters are used to display repeating patterns of widgets, such as rows of tabular data or layouts such as a product listing.


1 Answers

create another class and return type like your required widget:

example related to my customButton i required in various classes:

 Widget customButton(title,context,ResponseCallback callBack,shadowColor) {
  return Container(
    margin: EdgeInsets.only(top: 20),
    height: 80,
    width: 150,
    decoration: BoxDecoration(
      color: Colors.blue,
      borderRadius: BorderRadius.circular(75),
      boxShadow: [
        BoxShadow(
          spreadRadius: 1,
          blurRadius: 4,
          offset: Offset(4, 3),
          color: shadowColor
        )
      ]
    ),
    child: FlatButton(
      onPressed: () {
        callBack(title);
      },
      child: Text(title,
          style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold)),
    ),
  );
}

used:

child: customButton(
   comparedArray[index].category, context, buttonCallHandle,Colors.black),),



buttonCallHandle(e) {
dynamic instanceUpdated = instance.where((element) => element.category == e).toList();
Navigator.of(context).pushNamed('/choice', arguments: instanceUpdated);

}

like image 117
Anil Kumar Avatar answered Oct 03 '22 07:10

Anil Kumar