Home > Net >  How to use a custom widget based on build-in widgets?
How to use a custom widget based on build-in widgets?

Time:11-26

I want to populate a column inside my scaffold body with my MyContainer widget, but I was not able to access properties of the parent widget in child widget. MyContainer class is working fine but using MyColumn widget does not.

Here is my code:

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Title(
              color: const Color(0xFFFFFFFF),
              child: const Text("Hello World App")),
        ),
        body: MyColumn(),
      ),
    );
  }
}

class MyContainer extends Container {
  late int numbr;
  MyContainer(numbr) {
    this.numbr = numbr;
  }

  @override
  // TODO: implement color
  Color? get color => Colors.blue;
  @override
  // TODO: implement child
  Widget? get child => Center(
        child: Text("Container $numbr",
            style: TextStyle(
                fontSize: 34, fontFamily: "Cursive", color: Colors.white)),
      );
}

class MyColumn extends Column {
  @override
  // TODO: implement children
  List<Widget> get children {
    for (int i = 1; i < 11; i  ) {
      this.children.add(MyContainer(i));
    }
    return this.children;
  }
}

CodePudding user response:

  1. Use the build-in Column widget and instantiate it like similar widgets: Column(), Text(), etc., instead of extending the class. Please refer to the official dart documentation here, to learn how to properly use the extends key word.

  2. You can´t just add multiple widgets to Scaffold´s body, since it expects a single widget (e.g., a Column, Text or Container).

  3. You can use a custom widget MyCustomColumn to configure your column (see code below), but you can also simply add a column to body and pass the List.generate method to its children property.

Here is a code example:

class MyCustomColumn extends StatelessWidget {
  const MyCustomColumn ({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(children: List.generate(11, (index) {
      return MyContainer(i);}
      ),
    );
  }
}
  • Related