Search code examples
flutterflutter-dependencies

Conflict in data types flutter


I'm trying to read an image into a Uint8List. However, I have two different functions to read the conflicting return types one being Future and the other Uint8List how do I resolve this issue:

pick_default_image() async {
  Uint8List? img = (await rootBundle.load('assets/logo_oinkgram.png')).buffer.asUint8List();
  print("Typeee");
  print(img.runtimeType);
  return img;
}

pickImage(ImageSource source) async {
  final ImagePicker _imagePicker = ImagePicker();
  XFile? _file = await _imagePicker.pickImage(source: source);

  if (_file != Null) {
    return await _file!.readAsBytes();
  }
}

Part where the functions are being used:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oinkgram/resources/auth_methods.dart';
import 'package:oinkgram/utils/utils.dart';

import '../widgets/text_field_input.dart';

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

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

class _SignUpScreenState extends State<SignUpScreen> {
  final TextEditingController _emailcontroller = TextEditingController();
  final TextEditingController _passwordcontroller = TextEditingController();
  final TextEditingController _usernamecontroller = TextEditingController();
  final TextEditingController _biocontroller = TextEditingController();
  Uint8List  _image = pick_default_image();

  @override
  void dispose() {
    super.dispose();
    _emailcontroller.dispose();
    _passwordcontroller.dispose();
    _usernamecontroller.dispose();
    _biocontroller.dispose();
  }

  void selectImage() async {
    Uint8List im = await pickImage(ImageSource.gallery);
    setState(() {
      // _image = im;
    });
  }

  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      // backgroundColor: Colors.white,
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(new FocusNode()),
          child: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(colors: [
                Color.fromRGBO(237, 67, 186, 1),
                Color.fromRGBO(237, 67, 186, 1),
                Color.fromRGBO(249, 181, 208, 1)
              ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
            ),
            padding: const EdgeInsets.symmetric(horizontal: 32),
            width: double.infinity,
            child: SingleChildScrollView(
              child: SizedBox(
                height: MediaQuery.of(context).size.height -
                    MediaQuery.of(context).padding.top,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    //logo
                    // SvgPicture.asset("assets/icon_oinkgram.svg",height: 64,color: Colors.pink.shade200,)
                    Flexible(
                      flex: 1,
                      child: Container(),
                    ),
                    Image.asset(
                      "assets/logo_oinkgram1.png",
                      height: 32,
                    ),

                    const SizedBox(height: 32),
                    Stack(
                      children: [
                        GestureDetector(
                          onTap: selectImage,
                          child: CircleAvatar(
                              radius: 64, backgroundImage: MemoryImage(_image)),
                        ),
                        Positioned(
                          bottom: -15,
                          left: 90,
                          child: IconButton(
                            onPressed: selectImage,
                            icon: const Icon(
                              Icons.add_a_photo,
                            ),
                          ),
                        ),
                      ],
                    ),

                    //EMAIL
                    const SizedBox(height: 32),
                    TextFieldInput(
                        textEditingController: _usernamecontroller,
                        hintText: "Enter a username",
                        textInputType: TextInputType.text),

                    const SizedBox(height: 24),

                    TextFieldInput(
                        textEditingController: _emailcontroller,
                        hintText: "Enter you Email",
                        textInputType: TextInputType.emailAddress),

                    const SizedBox(height: 24),

                    //PASSWORD
                    TextFieldInput(
                        textEditingController: _passwordcontroller,
                        hintText: "Enter your password",
                        isPass: true,
                        textInputType: TextInputType.text),
                    const SizedBox(
                      height: 24,
                    ),

                    TextFieldInput(
                        textEditingController: _biocontroller,
                        hintText: "write a bio to express yourself",
                        textInputType: TextInputType.text),

                    const SizedBox(height: 24),

                    InkWell(
                      onTap: () async {
                        String res = await AuthMethods().SignUpUser(
                            email: _emailcontroller.text,
                            username: _usernamecontroller.text,
                            password: _passwordcontroller.text,
                            bio: _biocontroller.text,
                            file: _image);
                        print(res);
                        if (res != "Success!") {
                          ShowAlertDialog(context, res);
                        }
                      },
                      child: Container(
                        child: const Text("Sign up"),
                        width: double.infinity,
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        decoration: const ShapeDecoration(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(4)),
                          ),
                          color: Colors.blue,
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 12,
                    ),
                    Flexible(
                      child: Container(),
                      flex: 1,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          child: const Text("Already have an account?"),
                          padding: const EdgeInsets.symmetric(vertical: 8),
                        ),
                        GestureDetector(
                          onTap: () {},
                          child: Container(
                            child: const Text(
                              " Sign in",
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontWeight: FontWeight.bold),
                            ),
                            padding: const EdgeInsets.symmetric(vertical: 8),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

I keep getting the error: type 'Future' is not a subtype of type 'Uint8List'


Solution

  • Wherever you want to use the function needs to be async as well. So you could do this instead:

    Uint8List? _image;
    
    @override
    void initState() {
      super.initState();
      pick_default_image();
    }
    
    pick_default_image() async {
      Uint8List? img = (await rootBundle.load('assets/logo_oinkgram.png')).buffer.asUint8List();
      setState(() {
        _image = img;
      });
    }
    

    And then you also need to handle the case when _image is still null in your Widget. for example this part:

                        GestureDetector(
                          onTap: selectImage,
                          child: CircleAvatar(
                              radius: 64, backgroundImage: MemoryImage(_image)),
                        ),
    

    maybe can be changed to

                        GestureDetector(
                          onTap: selectImage,
                          child: CircleAvatar(
                              radius: 64, backgroundImage: _image == null ? null : MemoryImage(_image)),
                        ),