简体   繁体   中英

How do I pass data to a widget in Flutter?

I have a json file containing a list of titles and songNumbers. I made a listview and used onTap and Navigator.push to send det data to a detail page. It works fine to display the data as text, but I want to play songs from local assets. I use audioplayers package and if I hardcode a songname it works, but I want to pass the songname into the play function to play the selected song. My code for det detail page look (a bit simplified and shortened) like this:

import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';

class SongDetail extends StatelessWidget {
  final String title;
  final String songNumber;

  final player = AudioCache();

  SongDetail(this.title, this.songNumber);

  @override
  Widget build(BuildContext context) {
    Widget titleSection = Container(
      decoration: BoxDecoration(
        color: Colors.blueGrey[50],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(left: 20.0),
            child: IconButton(icon: Icon(
                Icons.play_circle_filled,
                size: 40.0),
                onPressed: () { player.play('1.mp3'); },
              ),
          ),

I can use Text(this.title) and Text(this.songNumber) to display the title and songNumber as text. But how to get the data from songNumber into the onPressed function instead of the hardcoded '1.mp3'?

Bear in mind that I am a newbie who maybe has taken a to difficult task, but I like challenges :)

你试过这个吗?

onPressed: () { player.play('$songNumber.mp3'); },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM