ricky
ricky

Reputation: 35

calling future in initstate but reaccessing again cause ERROR flutter

so yes.. I'm kinda bonker on this one, my problem is I need future/void type data to be accessed to initial data (which I already resolve using initstate) . now here is the problem first take a look at this code I made

import 'package:date_form_field/date_form_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker_widget/image_picker_widget.dart';
import 'package:image_picker_widget/enum/image_picker_widget_shape.dart';
import 'package:mall_daur/functions/globalParse.dart';
import 'dart:async';
import 'dart:io';
import 'package:parse_server_sdk/parse_server_sdk.dart';

class EditProfil extends StatefulWidget {
  @override
  _EditProfilState createState() => _EditProfilState();
}

class _EditProfilState extends State<EditProfil> {


  TextEditingController _textFieldController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  var _imagektp;
  var _imagerek;
  var _imageprofil;
  int _norek ;
  String _namabank ;
  int _noktp  ;
  String _tgllahir ;
  String _tempatlahir ;
  String NL ;
  var _nama;

  @override
  void initState() {
    super.initState();
    Timer.run(() async {
      _nama = await UserAccess().NamaLengkap();
      print(_nama);
      return _nama;
    });
  }

  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          title: Text('Edit Profil'),
          centerTitle: true,
        ),
        body: Stack(
          children: [
            Container(
              height: deviceSize.height,
              width: deviceSize.width,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('assets/images/background1.jpeg'),
                      fit: BoxFit.cover
                  )
              ),
            ),
            SingleChildScrollView(
              child: Container(
                margin: EdgeInsets.fromLTRB(20.0, 100.0, 20.0, 100.0),
                padding: EdgeInsets.all(20.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30.0),
                  color: Colors.blueAccent,
                  boxShadow: [BoxShadow(
                      color: Colors.black,
                      blurRadius: 10.0,
                      offset: Offset(0, 2)
                  )],),
                child: Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      Center(
                        child: ImagePickerWidget(
                          diameter: 100,
                          initialImage: "https://apprecs.org/gp/images/app-icons/300/81/com.unzypsoft.rekeningbookapps2.jpg" ,
                          shape: ImagePickerWidgetShape.circle,
                          isEditable: true,
                          onChange: (File file) {
                                 _imageprofil = file;
                                 },
                        ),
                      ),
                      Center(
                        child: Text('Foto Profil'),
                      ),
                      SizedBox(height: 10.0,),
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text('Nama Lengkap'),
                      ),
                      SizedBox(height: 5.0,),
                      Container(
                        height: 35.0,
                        width: 1200.0,
                        decoration: BoxDecoration(
                          color: Colors.white
                        ),
                          child: TextButton(onPressed: () async {
                              await _inputName(context);
                              },
                              child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text(_nama))))

                  ]
                  ),
                ),
              ),
            )
          ],
        )
  ),
    );
  }

  Future<void> _inputName(BuildContext context) async {
    String valueText = '';
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Isi nama lengkapnya'),
            content: TextField(
              onChanged: (value) {
                setState(() {
                  valueText = value;
                });
              },
              controller: _textFieldController,
              decoration: InputDecoration(hintText: "Nama Lengkap"),
            ),
            actions: <Widget>[
              ElevatedButton(
                child: Text('Batal'),
                onPressed: () {
                  setState(() {
                    Navigator.pop(context);
                  });
                },
              ),
              ElevatedButton(
                child: Text('Ubah Nama'),
                onPressed: () {
                  setState(() async {
                    ParseUser currentUser = await ParseUser.currentUser() as ParseUser;
                    await currentUser..set('NamaLengkap', valueText);
                    await currentUser.save();
                    _nama = valueText;
                    await Navigator.pop(context);
                  });
                },
              ),
            ],
          );
        });}

        Future<void> _name(BuildContext context) async {
          ParseUser currentUser = await ParseUser.currentUser() as ParseUser;
          final name = await currentUser.get('NamaLengkap');
          return name;
        }
}

here is if anyone care for UserAccess class I made

import 'package:parse_server_sdk/parse_server_sdk.dart';

class UserAccess {

  Future<String> NamaLengkap() async {
    ParseUser currentUser = await ParseUser.currentUser() as ParseUser;
    String NL = await currentUser.get('NamaLengkap');
    return NL;
  }

}

so the result should be like this (note parsedata came up as RICKY DES SAFRY from currentuser)

the intent picture I want

now I pop to previous scaffold which is this and try to access EDIT PROFIL

pop to previous scaffold and then reenter back

by some dumb luck I get this!

the error entering editprofil class

here is the error run

======== Exception caught by widgets library =======================================================
The following assertion was thrown building EditProfil(dirty, dependencies: [MediaQuery], state: _EditProfilState#67b84):
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 378 pos 10: 'data != null'

The relevant error-causing widget was: 
  EditProfil file:///E:/MALLDAUR/mall_daur/lib/screens/profil.dart:44:31
When the exception was thrown, this was the stack: 
#2      new Text (package:flutter/src/widgets/text.dart:378:10)
#3      _EditProfilState.build (package:mall_daur/models/EditProfil.dart:111:42)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#6      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
...
====================================================================================================

now by strange events if I save the editprofile dart..I get back to this again like nothing is wrong!

yepp returning to normal for a while

but if I pop back to previous scaffold and return in here the problem persist again. can anyone help me with this?

Upvotes: 0

Views: 407

Answers (1)

Lai Zong Hao
Lai Zong Hao

Reputation: 46

because Text() Widget can't accept null in it

Container(
  height: 35.0,
  width: 1200.0,
  decoration: BoxDecoration(
    color: Colors.white
  ),
  child: TextButton(onPressed: () async {
      await _inputName(context);
      },
      child: Align(
          alignment: Alignment.centerLeft,
          child: Text("$_nama"))))

Your Text widget should put in a string interpolation like Text("$_name")

Upvotes: 2

Related Questions