Flutter: Localization. putting AppLocalizations.of(context)!.header in a list of objects of type string && Access List In Another Class

Issue

I can now add AppLocalizations.of(context)!.header to the list but how can i call the list in another class without getting an empty list??

class DonationCategory extends StatefulWidget {
 const DonationCategory(
  {Key? key,
  required this.position,
  required this.name,
  required this.iconImage,
  required this.description,
  required this.images,
  required this.url})
  : super(key: key);
 final int position;
 final String name;
 final String iconImage;
 final String description;
 final List<String> images;
 final Uri url;

@override
State<DonationCategory> createState() => 
_DonationCategoryState();
}

List<DonationCategory> donate = [];

class _DonationCategoryState extends State<DonationCategory> {
@override
 void initState() {
super.initState();
SchedulerBinding.instance?.addPostFrameCallback((_) {
  setState(() {
    donate = [
      DonationCategory(
        position: 1,
        name: AppLocalizations.of(context)!.water, //use localization here
        iconImage: 'assets/images/who.gif',
        description:
            "“Ensure availability and sustainable management of water and sanitation for all”.  ",
        images: const [
          'assets/images/who.gif',
          'assets/images/who2.gif',
          // 'assets/images/water02.jpg',
          // 'assets/images/water02.jpg',
          // 'assets/images/water02.jpg',
        ],
        url: Uri.dataFromString(
            '<html><body><iframe src="https://ourworldindata.org/grapher/death-rates-unsafe-water" loading="lazy" style="width: 100%; height: 600px; border: 0px none;"></iframe></body></html>',
            mimeType: 'text/html'),
      ),
      DonationCategory(
        position: 2,
        name: AppLocalizations.of(context)!.food,
        iconImage: 'assets/images/food2.png',
        description:
            "The second of the UN's,
        images: [
          // 'https://cdn.pixabay.com/photo/2011/12/13/14/39/venus-11022_1280.jpg',
          // 'https://image.shutterstock.com/image-photo/solar-system-venus-second-planet-600w-515581927.jpg'
        ],
        url: Uri.dataFromString(
            '<html><body><iframe src="https://ourworldindata.org/grapher/global-hunger-index?country=IND~BGD~NPL~PAK" loading="lazy" style="width: 100%; height: 600px; border: 0px none;"></iframe></body></html>',
            mimeType: 'text/html'),
      ),
      DonationCategory(
        position: 3,
        name: AppLocalizations.of(context)!.health,
        iconImage: 'assets/images/hospital2.jpg',
        description:
            "In several . “Small contributions quickly add up if enough people take up the cause.”",
        images: [
          // 'https://cdn.pixabay.com/photo/2011/12/13/14/31/earth-11015_1280.jpg',
          // 'https://cdn.pixabay.com/photo/2011/12/14/12/11/astronaut-11080_1280.jpg',
          // 'https://cdn.pixabay.com/photo/2016/01/19/17/29/earth-1149733_1280.jpg',
          // 'https://image.shutterstock.com/image-photo/3d-render-planet-earth-viewed-600w-1069251782.jpg'
        ],
        url: Uri.dataFromString(
            '<html><body><iframe src="https://ourworldindata.org/grapher/dalys-rate-from-all-causes" loading="lazy" style="width: 100%; height: 600px; border: 0px none;"></iframe></body></html>',
            mimeType: 'text/html'),
      ),
      DonationCategory(
        position: 4,
        name: AppLocalizations.of(context)!.education,
        iconImage: 'assets/images/educated.png',
        description:
            "It is estimated that 101 million additional children and young people (from grades 1 to 8)  ",
        images: [],
        url: Uri.dataFromString(
            '<html><body><iframe src="https://ourworldindata.org/grapher/out-of-school-girls-of-primary-school-age-by-world-region" loading="lazy" style="width: 100%; height: 600px; border: 0px none;"></iframe></body></html>',
            mimeType: 'text/html'),
      ),
      DonationCategory(
        position: 5,
        name: AppLocalizations.of(context)!.adequacy,
        iconImage: 'assets/images/poor.png',
        description:
            "Ending poverty to live in extreme poverty by 2030.",
        images: [],
        url: Uri.dataFromString(
            '<html><body><iframe src="https://ourworldindata.org/grapher/size-poverty-gap-countries?country=~BRA" loading="lazy" style="width: 100%; height: 600px; border: 0px none;"></iframe></body></html>',
            mimeType: 'text/html'),
      ),
    ];
  });
});

Now I want to call donate in this class

import 'package:flutter/material.dart';
import 'package:sdg_app2/constants.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'donation_data.dart';
import 'donate_details.dart';

class GivePage extends StatefulWidget {
@override
_GivePageState createState() => _GivePageState();
}

class _GivePageState extends State<GivePage> {
 @override
  Widget build(BuildContext context) {
   return Scaffold(
    backgroundColor: kSecondaryColor,
    body: Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              colors: [kPrimaryColor, kSecondaryColor],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              stops: [0.3, 0.7])),
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(26.0),
              child: Column(
                children: <Widget>[
                  const Text(
                    'Give Support',
                    style: TextStyle(
                      fontFamily: 'Quicksand',
                      fontSize: 30,
                      color: Color(0xffffffff),
                      fontWeight: FontWeight.w900,
                    ),
                    textAlign: TextAlign.left,
                  ),
                  DropdownButton<String>(
                    items: const [
                      DropdownMenuItem(
                        child: Text(
                          'Where Needed',
                          style: TextStyle(
                            fontFamily: 'Quicksand',
                            fontSize: 24,
                            color: Color(0x7cdbf1ff),
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.left,
                        ),
                      ),
                    ],
                    onChanged: (value) {},
                    icon: const Padding(
                      padding: EdgeInsets.only(left: 16.0),
                    ),
                    underline: const SizedBox(),
                  ),
                ],
              ),
            ),
            Container(
              height: 500,
              padding: const EdgeInsets.only(left: 32),
              child: Swiper(
                itemCount: donate.length,
                itemWidth: MediaQuery.of(context).size.width - 2 * 64,
                layout: SwiperLayout.STACK,
                pagination: const SwiperPagination(
                  builder:
                      DotSwiperPaginationBuilder(activeSize: 20, space: 4),
                ),
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder: (context, a, b) => donationdetail(
                            donationInfo: donate[index], //I want to access donate here but it gives me an empty list
                          ),
                        ),
                      );
                    },
                    child: Stack(
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            const SizedBox(height: 100),
                            Card(
                              elevation: 8,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(32),
                              ),
                              color: Colors.white,
                              child: Padding(
                                padding: const EdgeInsets.all(32.0),
                                child: Column(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                  children: <Widget>[
                                    const SizedBox(height: 100),
                                    Text(
                                      donate[index].name.toString(), //I want to access donate here but it gives me an empty list
                                      style: const TextStyle(
                                        fontFamily: 'Quicksand',
                                        fontSize: 35,
                                        color: Color(0xff47455f),
                                        fontWeight: FontWeight.w900,
                                      ),
                                      textAlign: TextAlign.left,
                                    ),
                                    const Text(
                                      'Where Needed',
                                      style: TextStyle(
                                        fontFamily: 'Quicksand',
                                        fontSize: 23,
                                        color: Colors.black,
                                        fontWeight: FontWeight.w500,
                                      ),
                                      textAlign: TextAlign.left,
                                    ),
                                    const SizedBox(height: 32),
                                    Row(
                                      children: const <Widget>[
                                        Text(
                                          'Know more',
                                          style: TextStyle(
                                            fontFamily: 'Avenir',
                                            fontSize: 18,
                                            color: kPrimaryColor,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                        Icon(
                                          Icons.arrow_forward,
                                          color: kSecondaryColor,
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        Positioned(
                          right: 22,
                          bottom: 60,
                          child: Text(
                            donate[index].position.toString(), //I want to access donate here but it gives me an empty list
                            style: TextStyle(
                              fontFamily: 'Quicksand',
                              fontSize: 200,
                              color: Colors.black.withOpacity(0.08),
                              fontWeight: FontWeight.w900,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    ));

}
}

All i need to know is how to access donation in the other class without returning an empty list.

Please can anyone share an working solution or maybe edit my code? Thanks guys.

Solution

The simple way to solve this is to initialize the list inside initState.

List<DonationCategory> donate=[]; // declare like this

@override
void initState() {
    super.initState();
    SchedulerBinding.instance?.addPostFrameCallback((_) {
        setState(() {
            donate = [
                DonationCategory(
                1, 
                name: AppLocalizations.of(context) !.header, //use localization here
                iconImage: 'assets/images/who.gif', ... ),
            ];
        });
    });
}

Answered By – Harish

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.