Sittiphan Sittisak
Sittiphan Sittisak

Reputation: 885

How to dispose the controller for custom widget?

I have created my custom Widget that uses a controller like TextField.

Widget textField({...}) {
  TextEditingController controller = TextEditingController();

  return TextFormField(controller: controller, ...);
}

The main page uses this widget like this.

import 'package:flutter/material.dart';

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

  @override
  State<mainPage> createState() => _mainPageState();
}

class _mainPageState extends State<mainPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SafeArea(
          child: Column(
            children: [
              textField(),
            ],
          ),
        ),
      ),
    );
  }
}

The main page doesn't see the controller from textWidget. How to dispose of this controller?

Or I must create the controller on the main page and send this controller by using a parameter like this.

Widget textField({required TextEditingController controller}) {
  return TextFormField(controller: controller, ...);
}

Is it work? Another way?

Upvotes: 0

Views: 449

Answers (1)

Sujan Gainju
Sujan Gainju

Reputation: 4769

you can do that in two ways

  1. Make the textField widget stateful and dispose the controller on onDispose
  2. create the text editing controller in the mainPage and pass it to the textField widget

Upvotes: 1

Related Questions