Flutter BLoC Autofill A TextField on Event

Created At: 2024-05-12 04:36:32 Updated At: 2024-05-12 05:55:19

Here we will see how to autofill a form in Flutter using BLoC once an event is triggered. There could be a many different ways of doing it. 

First make sure you have flutter_bloc is installed. The we will create file call email_bloc.dart and put the code below

// Events

abstract class EmailEvent {}

class AutofillEmailEvent extends EmailEvent {}

// States

abstract class EmailState {}

class InitialEmailState extends EmailState {}

class FilledEmailState extends EmailState {

  final String email;

  FilledEmailState(this.email);

}

Here we have created EmailEvent abstruct class and then we have AutofillEmailEvent. This event would be called from our UI on a button click.

Then we have our states like InitialEmailState and FilledEmailState which extends our EmailState class.

Once the event is triggered, we will get our email from other functions or modules save inside the shared states using FilledEmailState.

// Bloc

class EmailBloc extends Bloc<EmailEvent, EmailState> {

  EmailBloc() : super(InitialEmailState()){

    on<AutofillEmailEvent>(onAutoFillEmail);

  }

  Future<void> onAutoFillEmail(

      AutofillEmailEvent event,

      Emitter<EmailState> emit,

      ) async {

    String savedEmail = await getSavedEmail();

    emit(FilledEmailState(savedEmail));

  }

  Future<String> getSavedEmail() async {

    // Your code to retrieve email from shared preferences

    // Example: SharedPreferences prefs = await SharedPreferences.getInstance();

    //           return prefs.getString('email') ?? '';

    return "example@example.com"; // Placeholder example

  }

}

In the bloc class we have the event AutofillEmailEvent, we call this from our UI and call the method onAutoFillEmail. Then after that we call getSavedEmail() which is followed by emit() function. Here we save the email then we got from earlier sources.

Emit() saves the email in the shared state and emit the states for the UI. 

The UI part is fairly simple, all we need to do is to call the AutoFillEmailEvent event using add() method of the flutter_bloc library.

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

import 'package:flutter_bloc/flutter_bloc.dart';

import 'email_bloc.dart';

void main() {

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      home: BlocProvider(

        create: (context) => EmailBloc(),

        child: MyHomePage(),

      ),

    );

  }

}

class MyHomePage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    final EmailBloc emailBloc = BlocProvider.of<EmailBloc>(context);

    return Scaffold(

      appBar: AppBar(

        title: Text("Autofill Email Example"),

      ),

      body: BlocBuilder<EmailBloc, EmailState>(

        builder: (context, state) {

          if (state is FilledEmailState) {

            return Center(

              child: Text(state.email),

            );

          } else {

            return Center(

              child: ElevatedButton(

                onPressed: () {

                  emailBloc.add(AutofillEmailEvent());

                },

                child: Text("Autofill Email"),

              ),

            );

          }

        },

      ),

    );

  }

}

Comment

Add Reviews