Home > Net >  Field 'urlVar' has not been initialized. error in Flutter
Field 'urlVar' has not been initialized. error in Flutter

Time:05-12

I have a settings page. On this page I configure "Url". I write it down and save it. Everything is simple. But I want to make sure that the next time I visit this page I have already seen the saved Url. I download it through the shared_preferences package (where I saved it). But there was an initialization error. Someone can help me with this. So that after opening the page I saw the saved Url and could edit it. My code

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test/setting/сonfiguration_styles.dart';



class Setting extends StatefulWidget {
  @override
  _EditSettingPageState createState() => _EditSettingPageState();
}

class _EditSettingPageState extends State<Setting> {

  late String urlVar;
  late TextEditingController _apiController =  TextEditingController();
  
  _loadvariable() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      urlVar = (prefs.getString('apiUrl'))?? "";
    });
  }


  @override
  void initState()   {
    _loadvariable()?? "";
    _apiController = TextEditingController( text: urlVar )
      ..addListener(() {
        setState(() {});
      });
    super.initState();
  }

  @override
  void dispose() {
    _apiController.dispose();
    super.dispose();
  }

    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: Container(
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: ListView(
              children: [
                TextFormField(
                  controller: _apiController,
                  cursorColor: StyleSettingPage.cursorColor,
                  style: StyleSettingPage.textBody,
                ),
                SizedBox(height: StyleSettingPage.heightBtwButtItem),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RaisedButton(
                      onPressed: seveSettingUrl,
                      child: Text(
                        "Save",
                        style:  StyleSettingPage.textButton
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
      );
    }


  Future<void> seveSettingUrl() async {
    SharedPreferences prefs = await SharedPreferences
        .getInstance();
    prefs.setString('apiUrl', _apiController.text);
  }

  }

CodePudding user response:

Check this out: First Page

import 'package:debounce/my_new_page.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class WritePage extends StatefulWidget {
  const WritePage({Key? key}) : super(key: key);

  @override
  State<WritePage> createState() => _WritePageState();
}

class _WritePageState extends State<WritePage> {
  final TextEditingController controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: ListView(
            children: [
              TextFormField(
                controller: controller,
              ),
              SizedBox(height: 100),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  RaisedButton(
                    onPressed: ()async{
                      SharedPreferences prefs = await SharedPreferences
                          .getInstance();
                      prefs.setString('apiUrl', controller.text);
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) =>  Edit()),
                      );
                    },
                    child: Text(
                      "Save",
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }


}

Second Page


import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Edit extends StatefulWidget {
  @override
  _EditSettingPageState createState() => _EditSettingPageState();
}

class _EditSettingPageState extends State<Edit> {

  var  urlVar;
  late TextEditingController _apiController =  TextEditingController();

  _loadvariable() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      urlVar = (prefs.getString('apiUrl'))?? "";
      print("Get URL VALUE: $urlVar");
    });
  }


  @override
  void initState()   {

    _loadvariable();

    super.initState();
  }

  @override
  void dispose() {
    _apiController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: Column(
              children: [TextFormField(
                controller: TextEditingController( text: urlVar ),
                decoration: InputDecoration(
                  // hintStyle: TextStyle(
                  //   color: Colors.purple,
                  //   fontStyle: FontStyle.italic,
                  // ),
                ),
              ),
                SizedBox(height: 100),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RaisedButton(
                      onPressed: ()async{
                        SharedPreferences prefs = await SharedPreferences
                            .getInstance();
                        prefs.setString('apiUrl', _apiController.text);
                        print("SET URL VALUE: $urlVar");
                      },
                      child: Text(
                        "Edit",
                      ),
                    )
                  ],
                )],
            )
          ),
        ),
      ),
    );
  }




}
  • Related