Home > Back-end >  I can't change text value in setstate function on Flutter
I can't change text value in setstate function on Flutter

Time:09-24

I am new to Flutter. I try to change a text value when the user clicks a button.

But at first, I'm getting the value of text from shared preferences. like below;

@override
  void initState() {
    super.initState();
    var tempstore = Store.empty;
    tempstore.getCurrent().then((value) => {
          setState(() {
            currentStore = value;
            storeName = currentStore.name;
          })
        });
  }

It works. But when I try to click the clear button and try to clear the store name it is not working. Here is another part of my code.

Text(storeName,style: const TextStyle(fontWeight: FontWeight.bold,fontSize: 20,color:Colors.red),)

 TextButton(
  child: const Text(
    "Clear", //AppLocalizations.of(context)!.edit,
    style: TextStyle(color: Colors.white),
  ),
  onPressed: () {
    setState(() {
      storeName = "";
    });
  },
)

I didn't find how can I change the variable of "storeName"?

Edit:

Here is all code;

class StoreSettings extends StatefulWidget {
  const StoreSettings({Key? key}) : super(key: key);
  @override
  State<StoreSettings> createState() => _StoreSettingsState();
}

class _StoreSettingsState extends State<StoreSettings> {
  String storeName = '';
  Store currentStore = Store.empty;

  @override
  void initState() {
    super.initState();
    var tempstore = Store.empty;
    tempstore.getCurrent().then((value) => {
          setState(() {
            currentStore = value;
            storeName = currentStore.name;
          })
        });
  }

  void clearCurrentStore() {
    SharedPreferences.getInstance()
        .then((prefs) => {prefs.remove(AppSettings.currentStore)});
  }

  @override
  Widget build(BuildContext context) => SimpleSettingsTile(
        title: 'Store Settings',
        subtitle: '',
        leading: const IconWidget(
          icon: Icons.store,
          color: Colors.grey,
        ),
        child: SettingsScreen(
          title: 'Store Settings',
          children: <Widget>[
            Container(
              width: 200,
              padding: const EdgeInsets.all(10),
              child: Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15.0),
                ),
                color: Palette.asBlue,
                elevation: 10,
                shadowColor: Colors.black,
                child: Column(
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(top: 10),
                      child: ListTile(
                        leading: const Icon(
                          Icons.store,
                          size: 70,
                          color: Colors.white,
                        ),
                        title: Text(
                          storeName,
                          style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                              color: Colors.red),
                        ),
                        subtitle: Text(
                          AppLocalizations.of(context)!.current_store,
                          style: TextStyle(
                              color: Colors.white.withOpacity(0.8),
                              fontSize: 10),
                        ),
                      ),
                    ),
                    ButtonBar(
                      children: <Widget>[
                        TextButton(
                          child: Text(
                            AppLocalizations.of(context)!.edit,
                            style: const TextStyle(color: Colors.white),
                          ),
                          onPressed: () {
                            Navigator.of(context).pushNamed(Routes.qr_reader,
                                arguments: Routes.storeSetting);
                          },
                        ),
                        TextButton(
                          child: const Text(
                            "Clear",
                            style: TextStyle(color: Colors.white),
                          ),
                          onPressed: () {
                            storeName = '';
                            setState(() {
                              clearCurrentStore();
                            });
                          },
                        )
                      ],
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      );
}

CodePudding user response:

Use Dartpad and copy paste the code.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
   return MaterialApp(
  title: 'Flutter Demo',
  debugShowCheckedModeBanner: false,
  theme: ThemeData(colorScheme: ColorScheme.light()),
  home: MyHomePage(),
   );
   }
 }


class MyHomePage extends StatefulWidget {


 @override
  _HomePageState createState() => _HomePageState();
}

@override
   class _HomePageState extends State<MyHomePage> {
   String storeName = '';

  @override
  void initState(){
   super.initState();

    storeName = 'MyValue';
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextButton(
          onPressed: () {
            // Respond to button press
            storeName = '';
            setState(() {});
          },
          child: Text("Clear"),
        ),
        SizedBox(height: 8.0),
        TextButton.icon(
          onPressed: () {
            // Respond to button press
          },
          icon: Icon(Icons.add, size: 18),
          label: Text(storeName),
        ),
      ],
    ),
  ),
   );
  }
 }

CodePudding user response:

keep your store string under setstate

TextButton(
                      child: const Text(
                        "Clear",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                        
                        setState(() {
                          storeName = '';
                          clearCurrentStore();
                        });
                      },
                    )
  • Related