mercredi 14 avril 2021

Flutter: Convert String to class name during runtime

Is it possible to "convert" a String which is dynamically generated in my code, into a class name, e.g. to use the class name as a key in a Map that has variables for each of keys?

My code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  // Suppose this is a dynamic list returned from a database query -
  // which for simplicity purposes is now "hard coded"
  final List<String> listFromDB = ['one', 'three', 'two'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: listFromDB.length,
          itemBuilder: (context, index) =>
              _listItemBuilder(context, index, listFromDB)),
    );
  }
}

Widget _listItemBuilder(BuildContext context, int index, List<String> list) {
  // suppose this is some map with translations of different languages. 
  final labels = Labels.translations['key'];

  final String key = list[index];
  // QUESTION: How can I use the above String key to "search" through the
  // AnyClass Map in order to return the corresponding value, e.g. "1" for the 
  // key "one"? How is it possible to "convert" a String into a key that can 
  // be used like so:  
  // print(labels.key) to return "1" if list[index] was "one"
  
  print(labels.key) // ERROR: Not compiling because key is a String


  return null;
}

// GENERATED: The below code can not be changed as it is generated

class Labels {
  static final Map<String, AnyClass> translations = {
    'key' : AnyClass(one: '1', two: '2', three: '3')
  };
}

class AnyClass {
  AnyClass({this.one, this.two, this.three});

  final String one;
  final String two;
  final String three;
}

I have read this old thread on GitHub on the same issue. But it seems there was no solution at that time. I also came across reflections in Dart but I am not sure whether they provide a solution in the above described case.

Thanks for any help and advice!





Aucun commentaire:

Enregistrer un commentaire